package com.bluesmart.mia;

import java.util.Calendar;
import java.util.Date;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.db.chart.model.LineSet;
import com.db.chart.model.Point;
import com.db.chart.view.LineChartView;
import com.db.chart.view.AxisController.LabelPosition;
import com.util.Constant;
import com.util.DensityUtil;
import com.util.MgqDataHandler;
import com.util.MgqRestClient;
import com.util.PreferencesUtils;
import com.util.Utils;
import com.widget.AverageView;
import com.widget.DrinkView;

import android.content.Context;
import android.content.Intent;
import android.graphics.Color;
import android.os.Handler;
import android.util.AttributeSet;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.view.View.OnClickListener;
import android.view.WindowManager;
import android.widget.BaseAdapter;
import android.widget.HorizontalScrollView;
import android.widget.ImageButton;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.RelativeLayout;
import android.widget.TextView;

public class HistoryActivity extends RelativeLayout implements OnClickListener{
	JSONArray mArray = new JSONArray();
//	HorizontalListViewAdapter mAdapter;
	ListViewAdapter mAdapterList;
	int mScreenWidth;
	int mScreenHeight;
	int mSelected = 0;
	
	boolean showGoal = true;
	boolean showAve = true;
	boolean showWeight = true;
	boolean showWeek = true;
	
	View mView;
	Context mContext;
	
	public HistoryActivity(Context context, AttributeSet attrs) {
		super(context, attrs);
		mContext = context;
		initView();
	}
	
	public HistoryActivity(Context context, AttributeSet attrs,int arg0) {
		super(context, attrs);
		mContext = context;
		initView();
	}
	
    public void initView()  {
		LayoutInflater mInflater = LayoutInflater.from(mContext);  
		mView = mInflater.inflate(R.layout.activity_history, null);  
		/*
		final HorizontalListView hlv = (HorizontalListView)mView.findViewById(R.id.hl); 
		mAdapter = new HorizontalListViewAdapter(mContext);
		hlv.setAdapter(mAdapter);  
        hlv.setOnItemClickListener(new OnItemClickListener()
        {
			@Override
			public void onItemClick(AdapterView<?> arg0, View arg1, int arg2,
					long arg3) {
				mSelected = arg2;
				mAdapter.notifyDataSetChanged();
				refereshList();
			}
        });
        */
    	mAdapterList = new ListViewAdapter(mContext);
    	final ListView listview = (ListView)mView.findViewById(R.id.listview); 
    	listview.setAdapter(mAdapterList);  

        mView.findViewById(R.id.filter0).setOnClickListener(this);
        mView.findViewById(R.id.filter1).setOnClickListener(this);
        mView.findViewById(R.id.btn0).setOnClickListener(this);
        mView.findViewById(R.id.btn1).setOnClickListener(this);
        mView.findViewById(R.id.btn_change).setOnClickListener(this);

        addView(mView);
        
        LinearLayout layout = (LinearLayout)findViewById(R.id.layout);
		for(int position = 0; position < 28; position++)
		{
			View convertView = mInflater.inflate(R.layout.item_chart, null);
			convertView.setTag(String.valueOf(position));
			convertView.setId(10000 + position);
			convertView.setOnClickListener(this);
			layout.addView(convertView);
		}
	}

    void refereshList()
	{
		int totalgoal = 0;
		JSONArray array = mArray.getJSONObject(mSelected).getJSONArray("goalData");
		if(array.size() > 0) totalgoal = array.getJSONObject(array.size() - 1).getIntValue("totalgoal");
		
		array = mArray.getJSONObject(mSelected).getJSONArray("data");
		int count = array.size();
		int total = 0;
		for(int i = 0; i < count; i++)
		{
			JSONObject item = array.getJSONObject(i);
			total += item.getIntValue("consumed_ml");
		}
		
		((TextView)mView.findViewById(R.id.goal)).setText(String.valueOf(totalgoal));
		((TextView)mView.findViewById(R.id.amount)).setText(String.valueOf(total));
		
		if(showWeek) 
		{
			((TextView)mView.findViewById(R.id.week)).setText(mContext.getString(R.string.time));
			((TextView)mView.findViewById(R.id.date)).setText(mArray.getJSONObject(mSelected).getString("date"));
		}
		else
		{
			array = mArray.getJSONObject(mSelected).getJSONArray("goalData");
			count = array.size();
			int goal = 0;
			for(int i = 0; i < count; i++)
			{
				JSONObject item = array.getJSONObject(i);
				goal += item.getIntValue("goal_ml");
			}
			
			((TextView)mView.findViewById(R.id.week)).setText(mContext.getString(R.string.date));
			((TextView)mView.findViewById(R.id.goal)).setText(String.valueOf(goal));
			
        	Calendar cal = Calendar.getInstance();
	        cal.setTime(new Date(System.currentTimeMillis()));
	        cal.add(Calendar.DAY_OF_MONTH, -7*(mArray.size() - mSelected) + 1);
        	String start = Utils.ConverToString(cal.getTime(), "MM/dd");

	        cal.setTime(new Date(System.currentTimeMillis()));
	        cal.add(Calendar.DAY_OF_MONTH, -7*(mArray.size() - mSelected - 1));
        	String end = Utils.ConverToString(cal.getTime(), "MM/dd");
        	
        	((TextView)mView.findViewById(R.id.date)).setText(start + " - " + end);
        
		}
		
		mAdapterList.notifyDataSetChanged();
	}
    
    public void setSelectedTab(int select)
    {
    	if(showWeek) mSelected = 20 + select;
    	else mSelected = 3;
    	
//    	refereshList();
    }
	
	public void sendChartHttpRequest(boolean show) {
		MgqDataHandler loginHandler = new MgqDataHandler(mContext, show, false) {
			@SuppressWarnings("unchecked")
			@Override
			public void onSuccess(String response) {
				JSONArray array = JSON.parseArray(response);
				mArray = new JSONArray();
				if(showWeek)
				{
					/*
					 *   {
    "date": "2015-09-28",
    "data": [
      {
        "date": "",
        "time": "",
        "goal_ml": 0,
        "consumed_ml": 0,
        "goal_temp": 0,
        "prepared_temp": 0,
        "average_min": 40,
        "average_max": 140
      }
    ],
    "goalData": [
      {
        "time": "06:00",
        "goal_ml": 120,
        "totalgoal": 120
      },
      {
        "time": "09:00",
        "goal_ml": 120,
        "totalgoal": 240
      },
      {
        "time": "12:00",
        "goal_ml": 120,
        "totalgoal": 360
      },
      {
        "time": "15:00",
        "goal_ml": 120,
        "totalgoal": 480
      },
      {
        "time": "18:00",
        "goal_ml": 120,
        "totalgoal": 600
      },
      {
        "time": "21:00",
        "goal_ml": 120,
        "totalgoal": 720
      }
    ]
  },
					 * */
					
					
					mScreenWidth = ((WindowManager) mContext.getSystemService(Context.WINDOW_SERVICE)).getDefaultDisplay().getWidth()/7;
					int count = array.size();
					for(int i = count - 1; i >= 0; i--)
					{
			/*			JSONObject obj = array.getJSONObject(i);
						JSONArray data = obj.getJSONArray("data");
						JSONArray goalData = obj.getJSONArray("goalData");
						*/
						mArray.add(array.getJSONObject(i));
					}
				}
				else 
				{
					int count = array.size();
					int page = count/7;
					page += count%7>0?1:0;
					mScreenWidth = ((WindowManager) mContext.getSystemService(Context.WINDOW_SERVICE)).getDefaultDisplay().getWidth()/page;

					JSONArray data = new JSONArray();
					JSONArray goal = new JSONArray();
					int len = 0;
					
					for(int i = count - 1; i >= 0; i--)
					{
						if(len > 0 && len%7 == 0)
						{
							JSONObject item = new JSONObject();
							item.put("data", data);
							item.put("goalData", goal);
							mArray.add(item);
							
							data = new JSONArray();
							goal = new JSONArray();
							
							data.add(array.getJSONObject(i).getJSONArray("data").get(0));
							goal.add(array.getJSONObject(i).getJSONArray("goalData").get(0));
						}
						else
						{
							data.add(array.getJSONObject(i).getJSONArray("data").get(0));
							goal.add(array.getJSONObject(i).getJSONArray("goalData").get(0));
						}
						
						if(i == 0)
						{
							JSONObject item = new JSONObject();
							item.put("data", data);
							item.put("goalData", goal);
							mArray.add(item);
						}
						len++;
					}
				}
				
				mScreenHeight = mView.findViewById(R.id.layout).getHeight();
				
				if(mSelected == 0 || mSelected >= mArray.size()) mSelected = mArray.size() - 1;
				

				for(int position = 0; position < 28; position++)
				{
					View convertView = findViewById(10000 + position);
					
					if(position != mSelected)
					{
						findViewById(10000 + position).setBackgroundColor(Color.parseColor("#0fc0db"));
					}
					else
					{
						findViewById(10000 + position).setBackgroundColor(Color.parseColor("#4762a8"));
					}
					
					if(position >= mArray.size())
					{
						findViewById(10000 + position).setVisibility(View.GONE);
						continue;
					}
					else
					{
						findViewById(10000 + position).setVisibility(View.VISIBLE);
					}
					
					JSONObject item = mArray.getJSONObject(position);

					DrinkView chart0 = (DrinkView)convertView.findViewById(R.id.chart0);
					LineChartView chart1 = (LineChartView)convertView.findViewById(R.id.chart1);
					AverageView chart2 = (AverageView)convertView.findViewById(R.id.chart2);
					
					chart1.setTag(String.valueOf(position));
					chart1.setOnClickListener(HistoryActivity.this);
					
					TextView time = (TextView)convertView.findViewById(R.id.time);
			        
			        android.view.ViewGroup.LayoutParams params = chart2.getLayoutParams();
			        params.width = mScreenWidth;
			        chart0.setLayoutParams(params);
			        chart1.setLayoutParams(params);
			        chart2.setLayoutParams(params);
			        
			        int height = 450;
			        if(!showWeek) height = 3200;
			        
			        chart0.setPoint(mArray,mScreenHeight,mScreenWidth,height,position);
			        LineSet lineSet = new LineSet();
			        
			        JSONArray goalData = mArray.getJSONObject(position).getJSONArray("goalData");
					for(int i = 0; i < goalData.size() + 1; i++)
					{
						if(i == goalData.size())
						{
							if(position < mArray.size() - 1)
							{
								JSONArray list = mArray.getJSONObject(position + 1).getJSONArray("goalData");
								if(list.size() > 0)
								{
									lineSet.addPoint(new Point("", list.getJSONObject(0).getFloatValue("goal_ml")));
									continue;
								}
							}

							lineSet.addPoint(new Point("", goalData.getJSONObject(0).getFloatValue("goal_ml")));
						}
						else
						{
							lineSet.addPoint(new Point("", goalData.getJSONObject(i).getFloatValue("goal_ml")));
						}
					}
			        
//					lineSet.setDotsColor(Color.RED);
					// Style line
					lineSet.setThickness(DensityUtil.dip2px(mContext, 2));
					lineSet.setColor(Color.parseColor("#fa7597"));
					// Style background fill
					lineSet.setFill(Color.TRANSPARENT);
//					lineSet.setFillColor(Color.RED);
					// Style type
					lineSet.setSmooth(true);
			        
					chart1.addData(lineSet);
					chart1.setXAxis(false);
					chart1.setYAxis(false);
					chart1.setYLabels(LabelPosition.NONE);
					chart1.setYLabels(LabelPosition.NONE);
					chart1.setAxisBorderValues(0, height, goalData.size() + 1);
					chart1.show();
			        
			        chart2.setPoint(mArray,mScreenHeight,mScreenWidth,height,position);
			        
			        if(showGoal && showAve)
			        {
			        	chart1.setVisibility(View.VISIBLE);
			        	chart2.setVisibility(View.VISIBLE);
			        }
			        else if(showGoal)
			        {
			        	chart1.setVisibility(View.VISIBLE);
			        	chart2.setVisibility(View.INVISIBLE);
			        }
			        else if(showAve)
			        {
			        	chart1.setVisibility(View.INVISIBLE);
			        	chart2.setVisibility(View.VISIBLE);
			        }
			        else
			        {
			        	chart1.setVisibility(View.INVISIBLE);
			        	chart2.setVisibility(View.INVISIBLE);
			        }
			        
			        if(showWeek)
			        {
			        	Date date = Utils.ConverToDate(item.getString("date"), "yyyy-MM-dd");
				        
				        Calendar cal = Calendar.getInstance();
				        cal.setTime(date);
				        int week = cal.get(Calendar.DAY_OF_WEEK) - 1;
				        if(week >= 7) week -= 7;
				        time.setText(Utils.dayOfWeek(mContext,week));
			        }
			        else
			        {
			        	Calendar cal = Calendar.getInstance();
				        cal.setTime(new Date(System.currentTimeMillis()));
				        cal.add(Calendar.DAY_OF_MONTH, -7*(mArray.size() - position) + 1);
			        	String start = Utils.ConverToString(cal.getTime(), "MM/dd");

				        cal.setTime(new Date(System.currentTimeMillis()));
				        cal.add(Calendar.DAY_OF_MONTH, -7*(mArray.size() - position - 1));
			        	String end = Utils.ConverToString(cal.getTime(), "MM/dd");
			        	
			        	time.setText(start + " - " + end);
			        }
				}
			
				
				final HorizontalScrollView scroll = (HorizontalScrollView)findViewById(R.id.scroll);
				if(showWeek)
				{
					new Handler().postDelayed((new Runnable() 
					{
						@Override public void run() 
						{ 
							scroll.scrollTo(22*mScreenWidth,0); 
						} 
					}),5);
				}
				else
				{
					new Handler().postDelayed((new Runnable() 
					{
						@Override public void run() 
						{ 
							scroll.scrollTo(0,0); 
						} 
					}),5);
				}
				
				refereshList();
			}
		};
		
		Date date = new Date(System.currentTimeMillis());
		Calendar ca = Calendar.getInstance();
		ca.setTime(date);
		ca.add(Calendar.DAY_OF_MONTH, -27);
		Date date0 = ca.getTime();

		String end = Utils.ConverToString(date, "yyyy-MM-dd");
		String start = Utils.ConverToString(date0, "yyyy-MM-dd");
		
		JSONObject params = new JSONObject();
		params.put("mia_un", PreferencesUtils.getString(mContext, "username"));
		params.put("pwd", PreferencesUtils.getString(mContext, "password"));
		params.put("start_date", start);
		params.put("end_date", end);
		if(showWeek) params.put("handType", "day");
		else params.put("handType", "week");
		
		MgqRestClient.postBody(Constant.SERVER_URL + "/sw/GetHistoryFeedData.ashx", JSON.toJSONString(params), loginHandler);
	}
	
	void changeView()
	{
		for(int position = 0; position < mArray.size(); position++)
		{
			View convertView = findViewById(10000 + position);
			
	        if(showGoal && showAve)
	        {
	        	convertView.findViewById(R.id.chart1).setVisibility(View.VISIBLE);
	        	convertView.findViewById(R.id.chart2).setVisibility(View.VISIBLE);
	        }
	        else if(showGoal)
	        {
	        	convertView.findViewById(R.id.chart1).setVisibility(View.VISIBLE);
	        	convertView.findViewById(R.id.chart2).setVisibility(View.INVISIBLE);
	        }
	        else if(showAve)
	        {
	        	convertView.findViewById(R.id.chart1).setVisibility(View.INVISIBLE);
	        	convertView.findViewById(R.id.chart2).setVisibility(View.VISIBLE);
	        }
	        else
	        {
	        	convertView.findViewById(R.id.chart1).setVisibility(View.INVISIBLE);
	        	convertView.findViewById(R.id.chart2).setVisibility(View.INVISIBLE);
	        }
		}
	}
	/*
	class HorizontalListViewAdapter extends BaseAdapter{  
		private LayoutInflater mInflater;  
		public HorizontalListViewAdapter(Context con){  
	        mInflater = LayoutInflater.from(con);  
	    }  
		
	    @Override  
	    public int getCount() {  
	        if(mArray != null) return mArray.size();  
	        return 0;
	    }  
	    
	    @Override  
	    public Object getItem(int position) {  
	        return position;  
	    }  

	    private class ViewHolder {  
	        private TextView time ;  
	        private HistoryView chart2;
	    }  
	    
	    @Override  
	    public long getItemId(int position) {  
	        return position;  
	    }  
	  
	    @Override  
	    public View getView(int position, View convertView, ViewGroup parent) {  
	    	ViewHolder vh = null;
	    	
	        if(true){
	        	vh = new ViewHolder();  
	            convertView = mInflater.inflate(R.layout.item_chart, null);  
	            vh.time = (TextView)convertView.findViewById(R.id.time);  
	            vh.chart2 = (HistoryView)convertView.findViewById(R.id.chart2); 
	            convertView.setTag(vh);  
	        }else{  
	            vh = (ViewHolder)convertView.getTag();  
	        }  
	        
	        JSONObject item = mArray.getJSONObject(position);
	        
	        android.view.ViewGroup.LayoutParams params = vh.chart2.getLayoutParams();
	        params.width = mScreenWidth;
	        vh.chart2.setLayoutParams(params);
	        
	        int height = 450;
	        if(!showWeek) height = 3000;
	        
	        if(showGoal && showAve) vh.chart2.setPoint(mArray,mScreenHeight,mScreenWidth,height,3,position);
	        else if(showGoal) vh.chart2.setPoint(mArray,mScreenHeight,mScreenWidth,height,2,position);
	        else if(showAve) vh.chart2.setPoint(mArray,mScreenHeight,mScreenWidth,height,1,position);
	        else vh.chart2.setPoint(mArray,mScreenHeight,mScreenWidth,height,0,position);
	        
	        if(showWeek)
	        {
	        	Date date = Utils.ConverToDate(item.getString("date"), "yyyy-MM-dd");
		        
		        Calendar cal = Calendar.getInstance();
		        cal.setTime(date);
		        int week = cal.get(Calendar.DAY_OF_WEEK) - 1;
		        if(week >= 7) week -= 7;
		        vh.time.setText(Utils.dayOfWeek(mContext,week));
	        }
	        else
	        {
	        	Calendar cal = Calendar.getInstance();
		        cal.setTime(new Date(System.currentTimeMillis()));
		        cal.add(Calendar.DAY_OF_MONTH, -7*(mArray.size() - position) + 1);
	        	String start = Utils.ConverToString(cal.getTime(), "MM/dd");

		        cal.setTime(new Date(System.currentTimeMillis()));
		        cal.add(Calendar.DAY_OF_MONTH, -7*(mArray.size() - position - 1));
	        	String end = Utils.ConverToString(cal.getTime(), "MM/dd");
	        	
		        vh.time.setText(start + " - " + end);
	        }
	        
	        if(position != mSelected)
			{
				convertView.setBackgroundColor(Color.parseColor("#0fc0db"));
			}
			else
			{
				convertView.setBackgroundColor(Color.parseColor("#4762a8"));
			}

	        return convertView;  
	    }  
	}  
	*/
	class ListViewAdapter extends BaseAdapter{  
		private LayoutInflater mInflater;  
		public ListViewAdapter(Context con){  
	        mInflater = LayoutInflater.from(con);  
	    }  
		
	    @Override  
	    public int getCount() {  
	        if(mArray != null && mArray.size() > 0) 
	        {
	        	JSONArray array = mArray.getJSONObject(mSelected).getJSONArray("data");
	        	return array.size();  
	        }
	        return 0;
	    }  
	    
	    @Override  
	    public Object getItem(int position) {  
	        return position;  
	    }  

	    private class ViewHolder {  
	        private TextView text0;
	        private TextView text1;
	        private TextView text2;
	    }  
	    
	    @Override  
	    public long getItemId(int position) {  
	        return position;  
	    }  
	  
	    @Override  
	    public View getView(int position, View convertView, ViewGroup parent) {  
	    	ViewHolder vh = null;
	    	
	        if(convertView==null){
	        	vh = new ViewHolder();  
	            convertView = mInflater.inflate(R.layout.item_history, null);  
	            vh.text0 = (TextView)convertView.findViewById(R.id.text0);  
	            vh.text1 = (TextView)convertView.findViewById(R.id.text1);  
	            vh.text2 = (TextView)convertView.findViewById(R.id.text2);  
	            convertView.setTag(vh);  
	        }else{  
	            vh = (ViewHolder)convertView.getTag();  
	        }  
	        

	        JSONArray array = mArray.getJSONObject(mSelected).getJSONArray("data");
	        JSONObject item = array.getJSONObject(position);
	        
	        vh.text1.setText(item.getString("consumed_ml"));
	        if(showWeek)
	        {
	        	vh.text2.setVisibility(View.INVISIBLE);
	        	vh.text0.setText(item.getString("time"));
	        }
	        else
	        {
	        	vh.text0.setText(item.getString("date").substring(5));
	        	
	        	array = mArray.getJSONObject(mSelected).getJSONArray("goalData");
		        item = array.getJSONObject(position);
	        	
	        	vh.text2.setVisibility(View.VISIBLE);
	        	vh.text2.setText(item.getString("goal_ml"));
	        }
	        
	        return convertView;  
	    }  
	}

	@Override
	public void onClick(View arg0) {
		if(arg0.getId() >= 10000 && arg0.getId() < 11000)
		{
			findViewById(10000 + mSelected).setBackgroundColor(Color.parseColor("#0fc0db"));
			mSelected = arg0.getId() - 10000;
			findViewById(10000 + mSelected).setBackgroundColor(Color.parseColor("#4762a8"));
			refereshList();
			
			return;
		}

		if(arg0.getTag() != null)
		{
			try
			{
				int position = Integer.valueOf((String)arg0.getTag());
				
				findViewById(10000 + mSelected).setBackgroundColor(Color.parseColor("#0fc0db"));
				mSelected = position;
				findViewById(10000 + mSelected).setBackgroundColor(Color.parseColor("#4762a8"));
				refereshList();
				
				return;
			}
			catch(Exception e){}
		}
		
		switch(arg0.getId())
		{
		case R.id.filter0:
			showGoal = !showGoal;
			if(showGoal)
			{
				((TextView)arg0).setCompoundDrawablesWithIntrinsicBounds(R.drawable.a10, 0, 0, 0);
				((TextView)arg0).setTextColor(Color.parseColor("#c45897"));
			}
			else
			{
				((TextView)arg0).setCompoundDrawablesWithIntrinsicBounds(R.drawable.a11, 0, 0, 0);
				((TextView)arg0).setTextColor(Color.parseColor("#30c45897"));
			}
			changeView();
			break;

		case R.id.filter1:
			showAve = !showAve;
			if(showAve)
			{
				((TextView)arg0).setCompoundDrawablesWithIntrinsicBounds(R.drawable.a08, 0, 0, 0);
				((TextView)arg0).setTextColor(Color.parseColor("#d4dd4a"));
			}
			else
			{
				((TextView)arg0).setCompoundDrawablesWithIntrinsicBounds(R.drawable.a09, 0, 0, 0);
				((TextView)arg0).setTextColor(Color.parseColor("#30d4dd4a"));
			}
			changeView();
			break;

		case R.id.btn0:
			showWeek = !showWeek;
			if(showWeek)
			{
				((ImageButton)arg0).setBackgroundResource(R.drawable.a19);
			}
			else
			{
				((ImageButton)arg0).setBackgroundResource(R.drawable.a20);
			}
			sendChartHttpRequest(true);
			break;
			
		case R.id.btn1:
			mContext.startActivity(new Intent(mContext,BabyMilkActivity.class));
			break;
			
		case R.id.btn_change:
			((MainPageActivity)mContext).changeView(R.id.btn0);
			break;
		}
	}  
}
